<?php

namespace App\Http\Controllers\Admin;

use App\Constants\AppConstants;
use App\Http\Controllers\Controller;
use App\Models\Coupon;
use App\Models\User;
use App\Models\Category;
use App\Models\Product;
use App\Services\CouponService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

/**
 * 后台优惠券管理控制器
 */
class AdminCouponController extends Controller
{
    protected CouponService $couponService;

    public function __construct(CouponService $couponService)
    {
        $this->couponService = $couponService;
    }

    /**
     * 优惠券列表
     */
    public function index(Request $request): Response
    {
        $query = Coupon::withCount(['userCoupons', 'distributions']);

        // 搜索
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('code', 'like', "%{$search}%");
            });
        }

        // 筛选类型
        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }

        // 筛选状态
        if ($request->filled('is_active')) {
            $query->where('is_active', $request->is_active);
        }

        $coupons = $query->orderBy('created_at', 'desc')->paginate(AppConstants::PAGINATION_ADMIN_DEFAULT);

        // 计算统计数据
        $stats = [
            'total_coupons' => Coupon::count(),
            'total_distributed' => \App\Models\UserCoupon::count(),
            'total_used' => \App\Models\UserCoupon::where('status', 'used')->count(),
            'total_discount' => \App\Models\UserCoupon::where('status', 'used')->sum('discount_amount') ?? 0,
        ];

        return Inertia::render('Admin/Coupons/Index', [
            'coupons' => $coupons,
            'stats' => $stats,
            'filters' => $request->only(['search', 'type', 'is_active']),
        ]);
    }

    /**
     * 创建优惠券页面
     */
    public function create(): Response
    {
        // 获取分类和商品数据供选择
        $categories = \App\Models\Category::select('id', 'name')->get();
        $products = \App\Models\Product::select('id', 'name', 'sku')->get();
        
        return Inertia::render('Admin/Coupons/Create', [
            'categories' => $categories,
            'products' => $products,
        ]);
    }

    /**
     * 保存优惠券
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:coupons,code',
            'type' => 'required|in:fixed,percent,shipping,full_reduction',
            'value' => 'required|numeric|min:0',
            'min_purchase' => 'nullable|numeric|min:0',
            'max_discount' => 'nullable|numeric|min:0',
            'total_quantity' => 'nullable|integer|min:0',
            'per_user_limit' => 'nullable|integer|min:0',
            'valid_days' => 'nullable|integer|min:1|max:365',
            'start_time' => 'nullable|date',
            'end_time' => 'nullable|date|after:start_time',
            'applicable_type' => 'required|in:all,category,product',
            'applicable_ids' => 'nullable|array',
            'stackable' => 'boolean',
            'description' => 'nullable|string',
            'usage_note' => 'nullable|string|max:500',
            'is_active' => 'boolean',
            'is_new_user_only' => 'boolean',
            'sort_order' => 'nullable|integer|min:0',
        ]);

        // 处理适用ID
        if ($validated['applicable_type'] === 'all') {
            $validated['applicable_ids'] = null;
        }

        // 处理时间
        if (isset($validated['valid_days']) && $validated['valid_days'] && !$validated['end_time']) {
            $validated['start_time'] = null;
        }

        Coupon::create($validated);

        return redirect()->route('admin.coupons.index')
            ->with('success', '优惠券创建成功');
    }

    /**
     * 编辑优惠券页面
     */
    public function edit(Coupon $coupon): Response
    {
        // 获取分类和商品数据供选择
        $categories = Category::select('id', 'name')->get();
        $products = Product::select('id', 'name', 'sku')->get();
        
        return Inertia::render('Admin/Coupons/Edit', [
            'coupon' => $coupon,
            'categories' => $categories,
            'products' => $products,
        ]);
    }

    /**
     * 更新优惠券
     */
    public function update(Request $request, Coupon $coupon)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:coupons,code,' . $coupon->id,
            'type' => 'required|in:fixed,percent,shipping,full_reduction',
            'value' => 'required|numeric|min:0',
            'min_purchase' => 'nullable|numeric|min:0',
            'max_discount' => 'nullable|numeric|min:0',
            'total_quantity' => 'nullable|integer|min:0',
            'per_user_limit' => 'nullable|integer|min:0',
            'valid_days' => 'nullable|integer|min:1|max:365',
            'start_time' => 'nullable|date',
            'end_time' => 'nullable|date|after:start_time',
            'applicable_type' => 'required|in:all,category,product',
            'applicable_ids' => 'nullable|array',
            'stackable' => 'boolean',
            'description' => 'nullable|string',
            'usage_note' => 'nullable|string|max:500',
            'is_active' => 'boolean',
            'is_new_user_only' => 'boolean',
            'sort_order' => 'nullable|integer|min:0',
        ]);

        // 处理适用ID
        if ($validated['applicable_type'] === 'all') {
            $validated['applicable_ids'] = null;
        }

        // 处理时间
        if (isset($validated['valid_days']) && $validated['valid_days'] && !$validated['end_time']) {
            $validated['start_time'] = null;
        }

        $coupon->update($validated);

        return redirect()->route('admin.coupons.index')
            ->with('success', '优惠券更新成功');
    }

    /**
     * 删除优惠券
     */
    public function destroy(Coupon $coupon)
    {
        // 检查是否有关联的用户优惠券
        if ($coupon->userCoupons()->exists()) {
            return back()->with('error', '该优惠券已被用户领取，无法删除');
        }

        $coupon->delete();

        return back()->with('success', '优惠券删除成功');
    }

    /**
     * 批量发放页面
     */
    public function distribute(Coupon $coupon): Response
    {
        // 获取用户统计数据
        $userStats = [
            'total_users' => User::count(),
            'active_users' => User::whereNotNull('email_verified_at')->count(), // 使用邮箱验证状态作为活跃用户
            'recent_users' => User::where('created_at', '>=', now()->subDays(30))->count(),
            'vip_users' => User::whereHas('orders', function($query) {
                $query->where('status', 'completed');
            })->count(),
        ];

        // 获取用户列表（用于搜索）
        $users = User::select('id', 'name', 'email', 'phone', 'created_at', 'email_verified_at')
            ->orderBy('created_at', 'desc')
            ->limit(50)
            ->get();

        return Inertia::render('Admin/Coupons/Distribute', [
            'coupon' => $coupon,
            'userStats' => $userStats,
            'users' => $users,
        ]);
    }

    /**
     * 发放给指定用户
     */
    public function sendToUsers(Request $request, Coupon $coupon)
    {
        $validated = $request->validate([
            'distribution_method' => 'required|in:manual,bulk,filter',
            'user_ids' => 'required_if:distribution_method,manual|array|min:1',
            'user_ids.*' => 'integer|exists:users,id',
            'quantity' => 'required|integer|min:1|max:10',
            'filters' => 'required_if:distribution_method,filter|array',
            'filters.user_type' => 'nullable|in:all,active,recent,vip',
            'filters.registration_date_from' => 'nullable|date',
            'filters.registration_date_to' => 'nullable|date|after_or_equal:filters.registration_date_from',
            'filters.min_order_amount' => 'nullable|numeric|min:0',
            'filters.max_order_amount' => 'nullable|numeric|min:0|gte:filters.min_order_amount',
            'filters.province' => 'nullable|string',
            'filters.city' => 'nullable|string',
            'notes' => 'nullable|string|max:500',
        ]);

        $userIds = [];

        if ($validated['distribution_method'] === 'manual') {
            $userIds = $validated['user_ids'];
        } elseif ($validated['distribution_method'] === 'bulk') {
            $userIds = User::whereNotNull('email_verified_at')->pluck('id')->toArray();
        } elseif ($validated['distribution_method'] === 'filter') {
            $query = User::query();
            
            // 用户类型筛选
            if (isset($validated['filters']['user_type'])) {
                switch ($validated['filters']['user_type']) {
                    case 'active':
                        $query->whereNotNull('email_verified_at');
                        break;
                    case 'recent':
                        $query->where('created_at', '>=', now()->subDays(30));
                        break;
                    case 'vip':
                        $query->whereHas('orders', function($q) {
                            $q->where('status', 'completed');
                        });
                        break;
                }
            }
            
            // 注册时间筛选
            if (isset($validated['filters']['registration_date_from'])) {
                $query->where('created_at', '>=', $validated['filters']['registration_date_from']);
            }
            if (isset($validated['filters']['registration_date_to'])) {
                $query->where('created_at', '<=', $validated['filters']['registration_date_to']);
            }
            
            // 消费金额筛选
            if (isset($validated['filters']['min_order_amount']) || isset($validated['filters']['max_order_amount'])) {
                $query->whereHas('orders', function($q) use ($validated) {
                    $q->where('status', 'completed');
                    if (isset($validated['filters']['min_order_amount'])) {
                        $q->where('total_amount', '>=', $validated['filters']['min_order_amount']);
                    }
                    if (isset($validated['filters']['max_order_amount'])) {
                        $q->where('total_amount', '<=', $validated['filters']['max_order_amount']);
                    }
                });
            }
            
            // 地区筛选
            if (isset($validated['filters']['province'])) {
                $query->whereHas('addresses', function($q) use ($validated) {
                    $q->where('province', 'like', '%' . $validated['filters']['province'] . '%');
                });
            }
            if (isset($validated['filters']['city'])) {
                $query->whereHas('addresses', function($q) use ($validated) {
                    $q->where('city', 'like', '%' . $validated['filters']['city'] . '%');
                });
            }
            
            $userIds = $query->pluck('id')->toArray();
        }

        if (empty($userIds)) {
            return back()->with('error', '没有找到符合条件的用户');
        }

        // 添加调试信息
        \Log::info('发放优惠券调试信息', [
            'coupon_id' => $coupon->id,
            'user_ids' => $userIds,
            'quantity' => $validated['quantity'],
            'distribution_method' => $validated['distribution_method']
        ]);

        $result = $this->couponService->batchDistribute(
            $coupon->id,
            $userIds,
            auth()->id(),
            $validated['notes'] ?? '',
            $validated['quantity']
        );

        if ($result['success']) {
            return back()->with('success', $result['message']);
        }

        return back()->with('error', $result['message']);
    }

    /**
     * 优惠券统计
     */
    public function statistics(Coupon $coupon): Response
    {
        // 获取统计数据
        $stats = [
            'total_distributed' => $coupon->userCoupons()->count(),
            'total_used' => $coupon->userCoupons()->used()->count(),
            'total_unused' => $coupon->userCoupons()->unused()->count(),
            'total_expired' => $coupon->userCoupons()->expired()->count(),
            'total_discount' => $coupon->userCoupons()->used()->sum('discount_amount'),
            'usage_rate' => $coupon->userCoupons()->count() > 0 
                ? round($coupon->userCoupons()->used()->count() / $coupon->userCoupons()->count() * 100, 2)
                : 0,
        ];

        // 获取最近7天的领取趋势
        $trends = $coupon->userCoupons()
            ->selectRaw('DATE(received_at) as date, COUNT(*) as count')
            ->where('received_at', '>=', now()->subDays(7))
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        return Inertia::render('Admin/Coupons/Statistics', [
            'coupon' => $coupon,
            'statistics' => $stats,
            'trends' => $trends,
        ]);
    }
}